const Router = require('koa-router')
let router = new Router()
const mongoose = require('mongoose')

router.post('/newOrder', async (ctx) => {
    const Order = mongoose.model('Order')
    let newOrder = new Order(ctx.request.body);
    await newOrder.save().then((res) => {
        ctx.body = {
            code: 200,
            data: {
                id: res.id
            },
            message: "下单成功"
        }
        const nodemailer = require('nodemailer');

        let transporter = nodemailer.createTransport({
            //host: 'smtp.qq.com',
            service: 'qq', // 使用了内置传输发送邮件 查看支持列表：https://nodemailer.com/smtp/well-known/
            port: 465, // SMTP 端口
            secureConnection: true, // 使用了 SSL
            secure: true, // secure:true for port 465, secure:false for port 587
            auth: {
                user: '357943642@qq.com',
                // 这里密码不是qq密码，是你设置的smtp授权码
                pass: 'zpoonglrtoyucbaa',
            }
        });

        let mailOptions = {
            from: '"天猫小店易佳购" <357943642@qq.com>', // sender address
            to: '1303380714@qq.com', // list of receivers
            subject: `用户【${newOrder.buyer}】手机号【${newOrder.mobile}】已下单`, // Subject line
            // 发送text或者html格式
            // text: 'Hello world?', // plain text body
            html: `<b>下单金额：${newOrder.amount}元</b><br /><b>送货地址：${newOrder.address}</b>` // html body
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message sent: %s', info.messageId);
            // Message sent: <04ec7731-cc68-1ef6-303c-61b0f796b78f@qq.com>
        });
    }).catch(error => {
        console.log(error)
        // 失败返回code=500，并返回错误信息
        ctx.body = {
            code: 500,
            message: error
        }
    })
})

// http://localhost:3000/order/newOrder

router.get('/getOrderList', async (ctx) => {
    let mobile = ctx.request.query.mobile
    const Order = mongoose.model('Order')
    let data = []
    await Order.find({ mobile: mobile }).sort({'id': -1}).exec().then(async (result) => {
        if (result) {
            data = result
        }
        ctx.body = { code: 200, total: result.length, data: result }
    }).catch(error => {  // 报错抛出
        console.log(error)
        ctx.body = { code: 500, message: error }
    })
})
// http://localhost:3000/order/getOrderList

module.exports = router